package org.example.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.example.util.SerializeUtil;

import java.util.List;

/**
 * @author mojito
 * @Classname RpcDecoder
 * @Description TODO
 * @Date 2020/7/22 下午9:30
 **/
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> generic;

    public RpcDecoder(Class<?> generic) {
        this.generic = generic;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
        int dataLength = in.readInt();
        if (dataLength < 0) {
            ctx.close();
        }
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);

        Object obj = SerializeUtil.deserialize(data, generic);
        System.out.println("decode success:----- ");
        out.add(obj);
    }
}
